package org.lztvn.elearning.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.lztvn.elearning.entities.Message;
import org.lztvn.elearning.unityclass.Notify;
import org.springframework.transaction.annotation.Transactional;

public class MesageImpl implements IMessageDAO{

	@PersistenceContext
	EntityManager em;
	@Override
	@Transactional
	public Message addMessage(Message message) {
		Query q = em.createQuery("SELECT max(u.orderMessage) FROM Message u WHERE (u.toUser = :fromA and u.fromUser = :fromB) or (u.toUser = :fromB and u.fromUser = :fromA)");
		q.setParameter("fromA", message.getFromUser());
		q.setParameter("fromB", message.getToUser());
		Long order = (Long)q.getSingleResult();
		if(order!=null){
			message.setOrderMessage(order+1);
		}else{
			message.setOrderMessage(0);
		}
		em.persist(message);
		em.flush();
		return message;
	}

}
